const api = require('../../utils/request.js');

Page({
  data: {
    orders: []
  },
  
  onLoad() {
    this.loadOrders();
  },

  onShow() {
    this.loadOrders();
  },
  
  async loadOrders() {
    try {
      wx.showLoading({
        title: '加载中...'
      });
      
      const userId = wx.getStorageSync('userId') || 1;
      const result = await api.getOrdersByUser(userId);
      
      // 处理后端返回的ResultVO格式
      const orders = (result.data || []).map(order => {
        return {
          ...order,
          createTime: this.formatTime(order.createTime),
          statusText: this.getStatusText(order.status),
          paymentMethodText: this.getPaymentMethodText(order.paymentMethod)
        };
      });
      
      this.setData({
        orders: orders
      });
    } catch (error) {
      console.error('加载订单失败:', error);
      wx.showToast({
        title: '加载订单失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return '';
    const date = new Date(timeStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
  },

  // 获取订单状态文本
  getStatusText(status) {
    const statusMap = {
      1: '待支付',
      2: '已支付',
      3: '已完成',
      4: '已取消'
    };
    return statusMap[status] || '未知';
  },

  // 获取支付方式文本
  getPaymentMethodText(method) {
    const methodMap = {
      1: '现金',
      2: '微信',
      3: '支付宝'
    };
    return methodMap[method] || '未知';
  },

  // 跳转到订单详情
  goToOrderDetail(e) {
    const orderNo = e.currentTarget.dataset.orderno;
    wx.navigateTo({
      url: `/pages/orderDetail/orderDetail?orderNo=${orderNo}`
    });
  }
});